package com.heima.wemadia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmNewsDto;
import com.heima.model.wemedia.dto.WmNewsListVo;
import com.heima.model.wemedia.dto.WmNewsPageReqDto;
import com.heima.model.wemedia.entity.KafkaMessageConstants;
import com.heima.model.wemedia.entity.WmMaterial;
import com.heima.model.wemedia.entity.WmNews;
import com.heima.wemadia.dao.WmMaterialDao;
import com.heima.wemadia.dao.WmNewsDao;
import com.heima.wemadia.dao.WmNewsMaterialDao;
import com.heima.wemadia.service.WmNewsService;
import com.heima.wemadia.utils.WmThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 自媒体文章表(WmNews)表服务实现类
 *
 * @author makejava
 * @since 2022-04-12 15:41:20
 */
@Service("wmNewsService")
public class WmNewsServiceImpl implements WmNewsService {
    @Resource
    private WmNewsDao wmNewsDao;
    @Resource
    private WmNewsMaterialDao wmNewsMaterialDao;
    @Resource
    private WmMaterialDao wmMaterialDao;
    @Resource
    private KafkaTemplate kafkaTemplate;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public WmNews queryById(Long id) {
        return this.wmNewsDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param wmNews 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<WmNews> queryByPage(WmNews wmNews, PageRequest pageRequest) {
        long total = this.wmNewsDao.count(wmNews);
        return new PageImpl<>(this.wmNewsDao.queryAllByLimit(wmNews, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param wmNews 实例对象
     * @return 实例对象
     */
    @Override
    public WmNews insert(WmNews wmNews) {
        this.wmNewsDao.insert(wmNews);
        return wmNews;
    }

    /**
     * 修改数据
     *
     * @param wmNews 实例对象
     * @return 实例对象
     */
    @Override
    public WmNews update(WmNews wmNews) {
        this.wmNewsDao.update(wmNews);
        return this.queryById(wmNews.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.wmNewsDao.deleteById(id) > 0;
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {

        if (StringUtils.isBlank(dto.getContent())||StringUtils.isBlank(dto.getTitle())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //image type
        List<Map> contentList = JSON.parseArray(dto.getContent(), Map.class);
        List<String> contentImages = contentList.stream()
                .filter(map -> "image".equals(map.get("type")))
                .map(map -> map.get("value").toString())
                .collect(Collectors.toList());

        List<String> coverImages = dto.getImages();
        if(dto.getType()== -1){
            if(contentImages.size()>=3){
                coverImages = contentImages.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(3);
            }else if(contentImages.size() > 0 && contentImages.size() <3){
                coverImages = contentImages.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(1);
            }else {
                coverImages = Collections.emptyList();
                wmNews.setType(0);
            }
        }

        if(CollectionUtil.isNotEmpty(coverImages)){
            wmNews.setImages(StringUtils.join(coverImages,","));
        }

        saveOrUpdate(wmNews);
        saveNewsMaterial(wmNews,coverImages,1);
        saveNewsMaterial(wmNews,contentImages,0);

        if(wmNews.getStatus()==1){
           kafkaTemplate.send(KafkaMessageConstants.WM_NEWS_AUTO_SCAN_TOPIC,wmNews.getId().toString());
        }
        return ResponseResult.okResult("文章发表成功");
    }

    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {

        dto.checkParam();

        Map<String, Object> queryParam = BeanUtil.beanToMap(dto);
        queryParam.put("userId",WmThreadLocalUtil.getUser().getId());

        PageHelper.startPage(dto.getPage(),dto.getSize());
        com.github.pagehelper.Page<WmNews> page = wmNewsDao.queryAll(queryParam);

        ResponseResult result = new PageResponseResult(page.getPageNum(),page.getPageSize(), (int) page.getTotal());
        result.setData(page.getResult());

        return result;
    }

    @Override
    public ResponseResult deleteNewsAndMaterial(Long id) {
        WmNews wmNews = wmNewsDao.queryById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (wmNews.getStatus()==9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"已发布文章不能删除");
        }
        wmNewsDao.deleteById(id);
        wmNewsMaterialDao.deleteByNewsId(id);
        return ResponseResult.okResult("删除成功");
    }

    @Override
    public ResponseResult newsList(WmNewsListVo vo) {

        return null;
    }

    private void saveNewsMaterial(WmNews wmNews, List<String> images, int type) {
        if (wmNews.getStatus() == 0) {
            return;
        }
        if(CollectionUtil.isEmpty(images)){
            return;
        }

        images = images.stream().distinct().collect(Collectors.toList());

        List<WmMaterial> list = wmMaterialDao.queryByUrls(images);
        List<Long> ids = list.stream().map(WmMaterial::getId).collect(Collectors.toList());

        if(images.size() != ids.size()){
            throw new RuntimeException("素材缺失");
        }
        wmNewsMaterialDao.insertByIds(wmNews.getId(),ids,type);
    }

    /**
    保存或修改文章
     */
    private void saveOrUpdate(WmNews wmNews) {
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable(1);
        if(wmNews.getId() == null){
            wmNewsDao.insert(wmNews);
        }

        wmNewsDao.update(wmNews);
        wmNewsMaterialDao.deleteByNewsId(wmNews.getId());

    }
}
